#include "RR.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

/**
 * 函数: calculateTimes
 * 功能: 根据时间片轮转调度算法计算每个进程的完成时间、周转时间和等待时间
 *
 * 参数:
 *  - processes: 指向包含多个进程信息的数组
 *  - n: 进程数量
 *  - time_slice: 时间片长度
 *
 * 描述:
 *  计算进程的完成时间，周转时间和等待时间并存在结构体中即可
 */
void
calculateTimes (Process *processes, int n, int time_slice)
{
  // TODO
    int time = 0; // 当前时间
    int completed = 0; // 已完成的进程数量
    bool done; // 用于标识是否有进程被执行

    // 初始化每个进程的 remaining_time
    for (int i = 0; i < n; i++) {
        processes[i].remaining_time = processes[i].burst_time;
    }

    while (completed != n) {
        done = true;

        for (int i = 0; i < n; i++) {
            if (processes[i].arrival_time <= time && processes[i].remaining_time > 0) {
                done = false;
                if (processes[i].remaining_time > time_slice) {
                    time += time_slice;
                    processes[i].remaining_time -= time_slice;
                } else {
                    time += processes[i].remaining_time;
                    processes[i].completion_time = time;
                    processes[i].remaining_time = 0;
                    completed++;
                }
            }
        }

        if (done) {
            time++;
        }
    }

    // 计算周转时间和等待时间
    for (int i = 0; i < n; i++) {
        processes[i].turnaround_time = processes[i].completion_time - processes[i].arrival_time;
        processes[i].waiting_time = processes[i].turnaround_time - processes[i].burst_time;
    }
}
